package com.rock.code.common.sso;


import com.rock.code.base.domain.Constants;
import com.rock.code.system.user.domain.TbSysLoginmsg;
import com.rock.code.system.user.service.TbSysLoginmsgService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取用户信息并写入到session中，配合CAS单点登录客户端一起使用
 */
public class SSOFilter implements Filter {
    public Log log = LogFactory.getLog(this.getClass());

    TbSysLoginmsgService tbSysLoginmsgServiceImpl;

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        /**
         * 获取用户名，由单点登录服务返回给门户
         * 从session中取出主账号 或者从账号和密码放入userCode, userPassword中
         */
        String userCode = (String) httpRequest.getSession().getAttribute("edu.yale.its.tp.cas.client.filter.user");
        TbSysLoginmsg user = (TbSysLoginmsg) httpRequest.getSession().getAttribute(Constants.SESSION_USER);
        try {
            // 如果session中用户信息为空，则去数据库中取用户信息。
            if (user == null) {
                if (userCode == null) {
                    chain.doFilter(httpRequest, httpResponse);
                    return;
                }

                Map<String, Object> param = new HashMap<String, Object>();
                param.put("loginId", userCode);
                user = tbSysLoginmsgServiceImpl.queryByParaMap(param);

                HttpSession session = httpRequest.getSession();
                session.setAttribute(Constants.SESSION_USER, user);
            }
            chain.doFilter(httpRequest, httpResponse);
        } catch (Exception e) {
            log.info(e);
            e.printStackTrace();
            httpResponse.setHeader("Charset", "GB2312");
            httpResponse.setContentType("text/html;charset=gb2312");
            httpResponse.setHeader("Cache-Control", "no-cache");
            httpResponse.getWriter().write(e.getMessage());
        }
    }

    @Override
    public void destroy() {

    }

    public void init(FilterConfig config) {
        ServletContext context = config.getServletContext();
        ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(context);
        tbSysLoginmsgServiceImpl = (TbSysLoginmsgService) ac.getBean("tbSysLoginmsgServiceImpl");
    }
}
